package com.oa.android.activity;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.oa.android.R;
import com.oa.android.adapter.EmilAdapter;
import com.oa.android.adapter.GwJsAdapter;
import com.oa.android.entry.Emil;
import com.oa.android.entry.Gwsf;
import com.oa.android.utils.UConstants;
import com.oa.android.utils.Util;
import com.oa.android.view.XListView;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;


/**
 * 公文接受列表
 *
 * @author -zouqh
 */
public class GwJsActivity extends Activity implements OnClickListener, XListView.IXListViewListener {

    private ImageView close;
    private TextView title, searchCru,addEmil;
    private XListView listView;
    ProgressDialog dialog;
    private List<Gwsf> emilList;
    private int page = 1;
    private int pageSize = 12;
    private int allPage = 0;
    private GwJsAdapter adapter;
    private String keyword = "";
    private String type;
    private String url;
    public static GwJsActivity activity;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.cao_gaox_activity);
        close = (ImageView) findViewById(R.id.close);
        title = (TextView) findViewById(R.id.title_text);
        searchCru = (TextView) findViewById(R.id.searchCru);
        addEmil= (TextView) findViewById(R.id.ritgh_text);
        activity=this;
        listView = (XListView) findViewById(R.id.listView);
        type=getIntent().getStringExtra("type");

        if (type.equals("1")){
            url=UConstants.JIS_FILE_LIST;
            title.setText("签收公文");
        }else{
            url=UConstants.CY_FILE_LIST;
            title.setText("传阅公文");
            addEmil.setText("新增");
            addEmil.setOnClickListener(this);
            addEmil.setVisibility(View.VISIBLE);
            ItemOnLongClick1();
        }
        searchCru.setHint("请输入公文名称");
        listView.setPullLoadEnable(true);// 向上滑动加载更多开启
        listView.setPullRefreshEnable(true);
        listView.setXListViewListener(this);
        listView.setFooterName("", false);
        close.setOnClickListener(this);
        searchCru.setOnClickListener(this);
        emilList = new ArrayList<>();

        adapter = new GwJsAdapter(this, emilList,type);
        listView.setAdapter(adapter);
        getDate(keyword);

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent=new Intent(GwJsActivity.this,DetailsGwjsActivity.class);
                Bundle bundle=new Bundle();
                bundle.putSerializable("gwsf",emilList.get(position-1));
                intent.putExtra("type",type);
                intent.putExtras(bundle);
                startActivity(intent);
            }
        });


    }


    private void ItemOnLongClick1() {
//注：setOnCreateContextMenuListener是与下面onContextItemSelected配套使用的
        listView.setOnCreateContextMenuListener(new View.OnCreateContextMenuListener() {

            public void onCreateContextMenu(ContextMenu menu, View v,
                                            ContextMenu.ContextMenuInfo menuInfo) {
                menu.setHeaderTitle("选择操作");
                menu.add(0,0,0,"修改");
//                menu.add(0,1,0,"删除");


            }
        });
    }

    // 长按菜单响应函数
    @Override
    public boolean onContextItemSelected(MenuItem item) {

        AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item
                .getMenuInfo();
//
        int id = (int)info.id;

        System.out.println("id----"+id);

        switch(item.getItemId()) {
            case 0:
                Intent intent=new Intent(GwJsActivity.this,AddCywjActivity.class);
                Bundle bundle=new Bundle();
                bundle.putSerializable("gwsf",emilList.get(id));
                intent.putExtra("type",type);
                intent.putExtras(bundle);
                startActivity(intent);
                break;

            case 1:
                //
//                pointDialog("确定删除文件夹吗？",id);

                break;



            default:
                break;
        }

        return super.onContextItemSelected(item);

    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub

        Intent intent;
        switch (v.getId()) {
            case R.id.close:
                finish();
                break;

            case R.id.searchCru:
                intent = new Intent(this, SearchActivity.class);
                startActivityForResult(intent, 1);
                break;

            case R.id.ritgh_text:
                intent = new Intent(this, AddCywjActivity.class);
                startActivity(intent);
                break;

            default:
                break;
        }
    }

    public void setResh(){
        page=1;
        emilList.clear();
        adapter.notifyDataSetChanged();
        getDate(keyword);
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    if (page < allPage) {
                        page++;
                        getDate(keyword);
                    } else {
                        listView.setFooterName("", false);
                    }
                    break;

            }

        }
    };




    //获取接收公文列表
    private void getDate(String selstr) {
        dialog = ProgressDialog.show(this, null, "加载中...", true, false);
        RequestParams params = new RequestParams(url);
        params.addBodyParameter("LKind", "OA");
        params.addBodyParameter("EmpId", UConstants.EmpId);
        params.addBodyParameter("Title", selstr);
        params.addBodyParameter("GWLX", type);
        params.addBodyParameter("page", page + "");
        params.addBodyParameter("rows", pageSize + "");
        x.http().get(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Util.printLog("getMerchants------------onSuccess-----", result);
                if (dowmUp){
                    onLoad();
                }
                if (result.length() > 0) {
                    try {
                        JSONObject object = new JSONObject(result);
                        allPage = Integer.parseInt(object.getString("total"));
                        allPage = (int) Math.ceil((double) allPage / pageSize);
                        boolean success = object.getBoolean("success");
//                        String msg = object.getString("msg");
                        if (success) {
                            Gson gson = new Gson();
                            Type lt = new TypeToken<List<Gwsf>>() {
                            }.getType();
                            List<Gwsf> list = gson.fromJson(object.getString("rows").toString(), lt);
//                            getJson(object.getString("rows").toString());
                            if (list != null && list.size() > 0) {
//								adapter = new CurstorAdapter(OlneSelectActivity.this, crutorJluList);
//								listView.setAdapter(adapter);
                                emilList.addAll(list);
                                adapter.notifyDataSetChanged();
                                if (page == allPage) {
                                    listView.setFooterName("", false);
                                } else if (page <= allPage) {
                                    listView.setFooterVisibility(true);
                                }

                            } else {
                                Toast.makeText(x.app(), "暂无公文！", Toast.LENGTH_LONG).show();
                            }

                        } else {
                            Toast.makeText(x.app(), "暂无公文！", Toast.LENGTH_LONG).show();
                        }
//                        Toast.makeText(x.app(), msg, Toast.LENGTH_LONG).show();
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
                dialog.dismiss();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Util.printLog("getMerchants------------onError-----", ex.getMessage() + "");

                Toast.makeText(x.app(), "获取数据失败！", Toast.LENGTH_LONG).show();
                dialog.dismiss();
            }

            @Override
            public void onCancelled(CancelledException cex) {

                Toast.makeText(x.app(), "cancelled", Toast.LENGTH_LONG).show();
                Util.printLog("getMerchants------------onCancelled-----", cex.getMessage() + "");
                dialog.dismiss();
            }

            @Override
            public void onFinished() {

            }
        });
    }



    boolean dowmUp;
    @Override
    public void onRefresh() {
        dowmUp=true;
        setResh();

    }

    @Override
    public void onLoadMore() {
        handler.sendEmptyMessage(1);
        onLoad();


    }

    private void onLoad() {
        listView.stopRefresh();
        listView.stopLoadMore();
        listView.setRefreshTime("刚刚");
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1) {
            if (resultCode == RESULT_OK) {
                if (data != null) {
                    keyword = data.getStringExtra("keyword");
                    emilList.clear();
                    page = 1;
                    adapter.notifyDataSetChanged();
                    getDate(keyword);

                }
            }
        }

    }
}
